<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{MerchantApplication, MerchantPaymentConfig, PlatformConfig};
use think\facade\{Db, Log};
use think\Request;

class SettingController extends BaseController
{
    /**
     * 获取应用配置
     */
    public function getAppConfig(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            $config = MerchantApplication::where('merchant_id', $merchant_id)
                ->field(['id', 'application_name', 'application_type', 'app_id', 'status'])
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $config]);
        } catch (\Exception $e) {
            Log::error('获取应用配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新应用配置
     */
    public function updateAppConfig(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MerchantApplication');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            $app = MerchantApplication::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$app) {
                return json(['code' => 1, 'msg' => '应用不存在']);
            }
            
            $app->save([
                'app_id' => $params['app_id'],
                'app_secret' => $params['app_secret'],
                'token' => $params['token'] ?? '',
                'encoding_aes_key' => $params['encoding_aes_key'] ?? '',
                'status' => $params['status'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('更新应用配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取支付配置
     */
    public function getPaymentConfig(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            $config = MerchantPaymentConfig::where('merchant_id', $merchant_id)
                ->field(['id', 'payment_method', 'status'])
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $config]);
        } catch (\Exception $e) {
            Log::error('获取支付配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新支付配置
     */
    public function updatePaymentConfig(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('MerchantPaymentConfig');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            $payment = MerchantPaymentConfig::where([
                'id' => $params['id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$payment) {
                return json(['code' => 1, 'msg' => '支付配置不存在']);
            }
            
            $payment->save([
                'payment_config' => json_encode($params['payment_config']),
                'status' => $params['status'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('更新支付配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取基础配置
     */
    public function getBaseConfig(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            // 获取平台默认配置
            $platform_config = PlatformConfig::where('group_name', 'base')
                ->column('config_value', 'config_key');
            
            // 获取商家自定义配置
            $merchant_config = MerchantApplication::where('merchant_id', $merchant_id)
                ->value('additional_info');
            
            $config = array_merge(
                $platform_config,
                $merchant_config ? json_decode($merchant_config, true) : []
            );
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $config]);
        } catch (\Exception $e) {
            Log::error('获取基础配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新基础配置
     */
    public function updateBaseConfig(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $app = MerchantApplication::where('merchant_id', $merchant_id)->find();
            if (!$app) {
                return json(['code' => 1, 'msg' => '商家应用不存在']);
            }
            
            $app->save([
                'additional_info' => json_encode($params),
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Log::error('更新基础配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 